package com.yuqiangz.lock;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author 赵雨强
 * @create 2021/7/10 13:48
 * @description 使用Lock接口的实现类创建
 */
class LockTicket{
    private int number = 30;
    private final ReentrantLock lock = new ReentrantLock();

    public void sale(){
        lock.lock();
        try {
            //判断是否有票
            if(number > 0) {
                System.out.println(Thread.currentThread().getName()+" ：卖出"+(number--)+" 剩余："+number);
            }
        } finally {
            lock.unlock();
        }
    }
}


public class LockSaleTicket {
    //第二步 创建多个线程，调用资源类的操作方法
    //创建三个线程
    public static void main(String[] args) {

        LockTicket ticket = new LockTicket();

        new Thread(()-> {
            for (int i = 0; i < 40; i++) {
                ticket.sale();
            }
        },"AA").start();

        new Thread(()-> {
            for (int i = 0; i < 40; i++) {
                ticket.sale();
            }
        },"BB").start();

        new Thread(()-> {
            for (int i = 0; i < 40; i++) {
                ticket.sale();
            }
        },"CC").start();
    }
}
